package com.example.controller;

import com.example.model.MerchantService;
import com.example.service.MerchantServiceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 商家服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/merchant-services")
@Tag(name = "商家服务管理", description = "商家服务相关接口")
public class MerchantServiceController {

    @Autowired
    private MerchantServiceService merchantServiceService;

    @PostMapping
    @Operation(summary = "创建商家服务")
    public ResponseEntity<Map<String, Object>> createService(
            @RequestBody MerchantService service,
            Authentication authentication) {
        
        try {
            // 设置商家ID
            service.setMerchantId(authentication.getName());

            MerchantService savedService = merchantServiceService.createService(service);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "服务创建成功");
            response.put("data", savedService);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("创建服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新商家服务")
    public ResponseEntity<Map<String, Object>> updateService(
            @PathVariable Long id,
            @RequestBody MerchantService service) {
        
        try {
            MerchantService updatedService = merchantServiceService.updateService(id, service);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "服务更新成功");
            response.put("data", updatedService);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("更新服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/{id}/publish")
    @Operation(summary = "发布服务")
    public ResponseEntity<Map<String, Object>> publishService(@PathVariable Long id) {
        try {
            merchantServiceService.publishService(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "服务发布成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("发布服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "发布服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/{id}/suspend")
    @Operation(summary = "暂停服务")
    public ResponseEntity<Map<String, Object>> suspendService(@PathVariable Long id) {
        try {
            merchantServiceService.suspendService(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "服务暂停成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("暂停服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "暂停服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除服务")
    public ResponseEntity<Map<String, Object>> deleteService(@PathVariable Long id) {
        try {
            merchantServiceService.deleteService(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "服务删除成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("删除服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取服务详情")
    public ResponseEntity<Map<String, Object>> getServiceById(@PathVariable Long id) {
        try {
            Optional<MerchantService> serviceOpt = merchantServiceService.getServiceByIdAndIncrementViewCount(id);
            
            Map<String, Object> response = new HashMap<>();
            if (serviceOpt.isPresent()) {
                response.put("success", true);
                response.put("data", serviceOpt.get());
            } else {
                response.put("success", false);
                response.put("message", "服务不存在");
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取服务详情失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取服务详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/merchant/{merchantId}")
    @Operation(summary = "获取商家的服务列表")
    public ResponseEntity<Map<String, Object>> getServicesByMerchant(
            @PathVariable String merchantId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<MerchantService> services = merchantServiceService.getServicesByMerchant(merchantId, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取商家服务列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取商家服务列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/my-services")
    @Operation(summary = "获取我的服务列表")
    public ResponseEntity<Map<String, Object>> getMyServices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        
        try {
            String merchantId = authentication.getName();
            Page<MerchantService> services = merchantServiceService.getServicesByMerchant(merchantId, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取我的服务列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取我的服务列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/published")
    @Operation(summary = "获取已发布的服务列表")
    public ResponseEntity<Map<String, Object>> getPublishedServices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<MerchantService> services = merchantServiceService.getPublishedServices(page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取已发布服务列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取已发布服务列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/category/{category}")
    @Operation(summary = "根据分类获取服务")
    public ResponseEntity<Map<String, Object>> getServicesByCategory(
            @PathVariable String category,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            MerchantService.ServiceCategory serviceCategory = MerchantService.ServiceCategory.valueOf(category.toUpperCase());
            Page<MerchantService> services = merchantServiceService.getServicesByCategory(serviceCategory, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("根据分类获取服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "根据分类获取服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/recommended")
    @Operation(summary = "获取推荐服务")
    public ResponseEntity<Map<String, Object>> getRecommendedServices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<MerchantService> services = merchantServiceService.getRecommendedServices(page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取推荐服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取推荐服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/popular")
    @Operation(summary = "获取热门服务")
    public ResponseEntity<Map<String, Object>> getPopularServices(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<MerchantService> services = merchantServiceService.getPopularServices(page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取热门服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取热门服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/search")
    @Operation(summary = "搜索服务")
    public ResponseEntity<Map<String, Object>> searchServices(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        try {
            Page<MerchantService> services = merchantServiceService.searchServices(keyword, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("搜索服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "搜索服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/price-range")
    @Operation(summary = "根据价格范围搜索服务")
    public ResponseEntity<Map<String, Object>> getServicesByPriceRange(
            @RequestParam BigDecimal minPrice,
            @RequestParam BigDecimal maxPrice,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        try {
            Page<MerchantService> services = merchantServiceService.getServicesByPriceRange(minPrice, maxPrice, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("根据价格范围搜索服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "根据价格范围搜索服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/area/{area}")
    @Operation(summary = "根据服务区域搜索服务")
    public ResponseEntity<Map<String, Object>> getServicesByArea(
            @PathVariable String area,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        try {
            Page<MerchantService> services = merchantServiceService.getServicesByArea(area, page, size);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("根据服务区域搜索服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "根据服务区域搜索服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @PostMapping("/{id}/favorite")
    @Operation(summary = "收藏服务")
    public ResponseEntity<Map<String, Object>> favoriteService(@PathVariable Long id) {
        try {
            merchantServiceService.incrementFavoriteCount(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "收藏成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("收藏服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "收藏服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @DeleteMapping("/{id}/favorite")
    @Operation(summary = "取消收藏服务")
    public ResponseEntity<Map<String, Object>> unfavoriteService(@PathVariable Long id) {
        try {
            merchantServiceService.decrementFavoriteCount(id);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "取消收藏成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("取消收藏服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消收藏服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取服务统计信息")
    public ResponseEntity<Map<String, Object>> getServiceStatistics() {
        try {
            Map<String, Object> statistics = merchantServiceService.getServiceStatistics();

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", statistics);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取服务统计信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取服务统计信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/latest")
    @Operation(summary = "获取最新发布的服务")
    public ResponseEntity<Map<String, Object>> getLatestServices(
            @RequestParam(defaultValue = "10") int limit) {

        try {
            List<MerchantService> services = merchantServiceService.getLatestServices(limit);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取最新服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取最新服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/top-rated")
    @Operation(summary = "获取评分最高的服务")
    public ResponseEntity<Map<String, Object>> getTopRatedServices(
            @RequestParam(defaultValue = "5") int minReviews,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            List<MerchantService> services = merchantServiceService.getTopRatedServices(minReviews, limit);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", services);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            log.error("获取评分最高服务失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取评分最高服务失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
